//输入一个整数N
//产生N个1-100的随机数
//通过管道接收
//计算随机数之和
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <sys/wait.h>
#include <string.h>

#define PIPE_NAME "/tmp/myfifo"

char *MyGetString(char*pbuf,int size);

int main(int argc,char*argv[])
{
    int ret=0;
    int wfd=0;
    int size=0;
    char buf[64]="";
    if(access(PIPE_NAME,F_OK))
    {
        ret = mkfifo(PIPE_NAME,0666);
        if (ret<0)
        {
            printf("error");
            return 1;
        }
    }
    printf("write process before open\n");
    wfd = open(PIPE_NAME,O_RDONLY);
    printf("write process after open\n");
    if(wfd < 0)
    {
        printf("error");
        return 2;
    }
    while (1)
    {
        memset(buf,0,64);
        printf("Please your content:\n");
        MyGetString(buf,64);
        size=strlen(buf)+1;
        write(wfd,&size,sizeof(int));
        write(wfd,buf,size);
        if(strcmp(buf,"quit")==0)
        {
            break;
        }
    }
    
    close(wfd);
    wfd = -1;
    return 0;
}
char *MyGetString(char*pbuf,int size)
{
    char *p=NULL;
    int len=0;
    p = fgets(pbuf,size,stdin);
    if(NULL==p)
    {
        return NULL;
    }
    //判断用户本次输入有剩余
    len=strlen(pbuf);
    if(*(pbuf+len-1)=='\n')
    {
        *(pbuf+len-1)='\0';
    }
    else
    {
        while(getchar()!='\n')
        {

        }
    }
    return p;
}